package org.nashua.tt151.utils;

public class Dictionary {
    public static class ReadOnlyDictionary extends Dictionary {
        public void put(String key,Object val){}
    }
    private String[] keys;
    private Object[] vals;
    public Dictionary(){
        this(new String[0],new Object[0]);
    }
    public Dictionary(String[] keys,Object[] vals){
        this.keys=keys;
        this.vals=vals;
    }
    public Dictionary(String key, Object val){
        this(new String[]{key},new Object[]{val});
    }
    private void add(String key, Object val) {
        // Add Key
        String[] k = keys;
        keys = new String[k.length+1];
        System.arraycopy(k,0,keys,0,k.length);
        keys[k.length]=key;
        // Add Value
        Object[] v = vals;
        vals = new Object[v.length+1];
        System.arraycopy(v,0,vals,0,v.length);
        vals[v.length]=val;
    }
    public void put(String key, Object val) {
        int i=indexOfKey(key);
        if (i==-1)
            add(key,val);
        else {
            keys[i]=key;
            vals[i]=val;
        }
    }
    public int indexOfKey(String key){
        for (int i=0;i<keys.length;i++) 
            if (keys[i].equals(key))
                return i;
        return -1;
    }
    public int indexOfVal(Object val) {
        for (int i=0;i<vals.length;i++) 
            if (vals[i].equals(val))
                return i;
        return -1;
    }
    public String keyOf(Object val){
        int i=indexOfVal(val);
        if (i==-1)
            return null;
        else
            return keys[i];
    }
    public Object get(String key){
        int i=indexOfKey(key);
        if (i==-1)
            return null;
        else
            return vals[i];
    }
    public boolean getBoolean(String key){
        return Genericless.toBoolean(get(key));
    }
    public double getDouble(String key){
        return Genericless.toDouble(get(key));
    }
    public float getFloat(String key){
        return Genericless.toFloat(get(key));
    }
    public int getInt(String key){
        return Genericless.toInt(get(key));
    }
    public String getString(String key){
        return get(key).toString();
    }
    public boolean hasKey(String key){
        return get(key)!=null;
    }
}
